package com.maozzi.service.acl.domain.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maozzi.common.enums.BizCodeEnum;
import com.maozzi.common.exception.BizException;
import com.maozzi.common.util.ParamCheckUtil;
import com.maozzi.service.acl.domain.RoleDomainService;
import com.maozzi.service.acl.repository.mapper.RoleMapper;
import com.maozzi.service.acl.repository.model.Role;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 权限 - 角色 domain service
 *
 * @author maozi
 */
@Service
public class RoleDomainServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleDomainService {

    @Override
    public Role getRole(Long roleId) {
        return this.getById(roleId);
    }

    @Override
    public Role addRole(Role role) {
        ParamCheckUtil.notNull(role, "参数错误");

        // 检查角色名称是否重复
        this.checkName(role.getName());

        role.setId(null);
        role.setCreateDate(null);
        role.setModifiedBy(null);
        role.setModifiedDate(null);
        role.setDeleted(null);

        this.save(role);

        return role;
    }

    /**
     * 检查角色名称是否重复
     *
     * @param name       名称
     * @param excludeIds 排除项
     */
    private void checkName(String name, Long... excludeIds) {
        LambdaQueryWrapper<Role> query = Wrappers.lambdaQuery(Role.class)
                .eq(Role::getName, name)
                .eq(Role::getDeleted, false);
        if (Objects.nonNull(excludeIds) && excludeIds.length > 0) {
            query.notIn(Role::getId, (Object[]) excludeIds);
        }

        long count = this.count(query);
        if (count > 0) {
            throw new BizException(BizCodeEnum.WRONG_PARAMETERS, "角色名称重复");
        }
    }

    @Override
    public Boolean editRole(Long roleId, Role role) {
        ParamCheckUtil.notNull(roleId, "角色ID为空");
        ParamCheckUtil.notNull(role, "参数错误");

        // 检查角色名称是否重复
        this.checkName(role.getName(), roleId);

        role.setModifiedDate(null);

        return this.update(role, Wrappers.lambdaUpdate(Role.class).eq(Role::getId, roleId));
    }

    @Override
    public Page<Role> rolePage(Page<Role> page, Wrapper<Role> query) {
        return this.page(page, query);
    }
}
